package com.java.controller.api;


import com.alibaba.fastjson.JSON;
import com.java.hfb.RequestHelper;
import com.java.pojo.vo.UserBindVo;
import com.java.result.Result;
import com.java.service.UserBindService;
import com.java.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 前端控制器
 * </p>
 *
 * @author Helen
 * @since 2021-07-08
 */

@Api("会员账号绑定")
@RestController
@RequestMapping("/api/core/userBind")
public class UserBindController {

    private static final Logger log = LoggerFactory.getLogger(UserBindController.class);
    @Resource
    private UserBindService userBindService;


    //通过请求获取请求头里的token 拿到userId
    @ApiOperation("账户绑定提交数据")
    @PostMapping("/auth/bind")
    public Result bind(UserBindVo userBindVo, HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        String formStr = userBindService.commitBindUser(userBindVo,userId);
        return Result.ok(formStr);
    }

    @ApiOperation("账户绑定异步回调")
    @PostMapping("/notify")
    public String notify(HttpServletRequest request){
        //汇付宝会在绑定后通过这个接口给我发送数据
        Map<String, Object> map = RequestHelper.switchMap(request.getParameterMap());
        log.info("账户绑定一步回调接受参数如下", JSON.toJSONString(map));
        //验签
        boolean signEquals = RequestHelper.isSignEquals(map);
        if(!signEquals){
            log.info("用户账号绑定异步回调签约验证错误:"+JSON.toJSONString(map));
            return "fail";
        }
        //用户绑定
        userBindService.notifybind(map);
        return "success";
    }


}

